<template>
	<view>
		<view class="mask" v-if="functionBox" @click="hideMask"></view>
		<view>
			<!-- <view class="status_bar uni-page-head" >
			<view class="uni-page-head-hd">
				<view class="uni-page-head-btn" @click="back"><i class="uni-btn-icon" style="color: rgb(0, 0, 0); font-size: 27px;"></i></view>
			</view>
			<view class="uni-page-head-bd">
				<view class="uni-page-head__title">{{ titleText }}</view>
			</view>
			<view class="more-group uni-page-head-hd">
				<image src="../../static/img/more.png" @click="groupInfo" style="width: 32px;height: 100%;margin-right: 6px;"></image>
			</view>
		</view> -->
			<view class="nav">
				<image class="back" @click="back" src="../../static/pages/back1.png"></image>
				<view class="nav-text">{{ titleText }}</view>
				<image class="issue" src="../../static/img/more.png" @click="groupInfo"></image>
			</view>
			<view class="content" @touchstart="hideDrawer">
				<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation"
					:scroll-top="scrollTop" :scroll-into-view="scrollToView" @scrolltoupper="loadHistory"
					upper-threshold="50">
					<view class="announcement" v-if="h_groupInfo" @click="toAnnouncement">
						<view class="a_close" @click.stop="closeGroupInfoFun">
							<image src="../../static/img/announcement_close.png" mode=""></image>
						</view>
						<view class="a_content">
							<view class="a_c_head">
								<image src="../../static/img/announcement.png" mode=""></image>
							</view>
							<view class="a_c_text">{{h_groupInfo.length>47?h_groupInfo.slice(0, 46):h_groupInfo}}
								<text class="a_c_text_particulars" v-if="h_groupInfo.length>47">【查看详情】</text>
							</view>
						</view>
					</view>
					<view class="row" style="padding-top: 20rpx;" v-for="(item, index) in msgList" :key="index"
						:id="item.ID" v-if="!item.isRevoked">
						<!-- 用户消息 -->
						<view class="funcBtn" :style="funcBox_position" v-if="functionBox == item.ID">
							<view class="func" @click="revokeMessage(item)">
								撤回
							</view>
							<view class="func" @click="copyText" v-if="item.type == TIM.TYPES.MSG_TEXT">
								复制
							</view>
						</view>
						<block>
							<!-- 自己发出的消息 -->
							<view class="my" v-if="item.flow == 'out'">
								<!-- 左-消息 -->
								<view class="left">
									<!-- 文字消息 -->
									<view @longpress="showFunctionBox(item)" :class="item.ID"
										v-if="item.type == TIM.TYPES.MSG_TEXT" class="bubble box-pandding">
										<rich-text :nodes="nodesFliter(item.payload.text)"></rich-text>
									</view>
									<!-- 图片消息 -->
									<view @longpress="showFunctionBox(item)" :class="item.ID"
										v-if="item.payload.data == 'chatFile'" class="bubble img" @tap="showPic(item)">
										<view class="chatImg">
											<image :src="item.payload.description" mode="widthFix"></image>
										</view>
									</view>
									<!-- 语言消息 -->
									<view @longpress="showFunctionBox(item)" v-if="item.payload.data == 'voiceFile'"
										class="bubble voice box-pandding" @tap="playVoice(item)"
										:class="playMsgid == item.ID ? 'play' : ''+item.ID">
										<view class="length">{{ item.payload.extension }}</view>
										<view class="icon my-voice"></view>
									</view>
									<!-- 视频消息 -->
									<view @longpress="showFunctionBox(item)" :class="item.ID"
										v-if="item.payload.data == 'videoFile'" class="bubble video">
										<!-- <video id="myVideo" :src="item.payload.description" @error="videoErrorCallback" controls></video> -->
										<view class="videoBox">
											<image class="playImg" @click="playVideo(item.payload.description)"
												src="../../static/play.png" mode=""></image>
										</view>
									</view>
									<view @longpress="showFunctionBox(item)" :class="item.ID"
										v-if="item.payload.data == 'mapFile'" class="bubble video map">
										<!-- <view class="map-text">{{ item.payload.description.message }}</view> -->
										<view class="map-content1" @click="checkMyLocation(item.payload.description)">
											<input placeholder="我的位置" style="width: 120rpx;" disabled="true">
											<image style="width: 32rpx;height: 32rpx;"
												src="../../static/my/location.png" mode=""></image>
										</view>
									</view>
								</view>
								<view class="left-img"
									:style="item.payload.data != 'chatFile' & 'redEnvelopeData' ?'':'background:rgb(229,229,229)' ">
								</view>
								<!-- 右-头像 -->
								<view class="right" @click="toUserHome(userInfo.id)">
									<image :src="userInfo.avatar"></image>
								</view>
							</view>
							<!-- 别人发出的消息 -->
							<view class="other" v-else>
								<!-- 左-头像 -->
								<view class="left" @click="toUserHome(null, item.avatar)">
									<image :src="item.avatar"></image>
								</view>
								<!-- 右-用户名称-时间-消息 -->
								<view class="right">
									<view class="username">
										<view class="name" style="margin-right: 5px;">{{ toUserName(item.avatar) }}
										</view>
										<view class="time">{{ timeFliter(item.time) }}</view>
									</view>
									<view class="right-img"
										:style="item.payload.data != 'chatFile' & 'redEnvelopeData' ?'':'background:rgb(229,229,229)' ">
									</view>
									<!-- 文字消息 -->
									<view v-if="item.type == TIM.TYPES.MSG_TEXT" class="bubble box-pandding">
										<rich-text :nodes="nodesFliter(item.payload.text)"></rich-text>
									</view>
									<view v-if="item.payload.data == 'chatFile'" class="bubble img"
										@tap="showPic(item)">
										<view class="chatImg">
											<image :src="item.payload.description" mode="widthFix"></image>
										</view>
									</view>
									<!-- 语言消息 -->
									<view v-if="item.payload.data == 'voiceFile'" class="bubble box-pandding voice"
										@tap="playVoice(item)" :class="playMsgid == item.ID ? 'play' : ''">
										<view class="icon other-voice"></view>
										<view class="length">{{ item.payload.extension }}</view>

									</view>
									<!-- 视频消息 -->
									<view v-if="item.payload.data == 'videoFile'" class="bubble video">
										<view class="videoBox">
											<image class="playImg" @click="playVideo(item.payload.description)"
												src="../../static/play.png" mode=""></image>
										</view>
									</view>
									<!-- 地图消息 -->
									<view v-if="item.payload.data == 'mapFile'" class="bubble video map"
										style="background-color: #2ec5f4;">
										<!-- <view class="map-text">{{ item.payload.description.message }}</view> -->
										<view class="map-content1" @click="checkMyLocation(item.payload.description)">
											<input style="width: 170rpx;" placeholder="我的位置" disabled="true" />
											<image style="width: 32rpx;height: 32rpx;"
												src="../../static/my/location.png" mode=""></image>
										</view>
									</view>
								</view>
							</view>
						</block>
					</view>
				</scroll-view>
			</view>
			<!-- 抽屉栏 -->
			<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
				<!-- 表情 -->
				<!-- <swiper class="emoji-swiper" :class="{ hidden: hideEmoji }" indicator-dots="true" duration="150">
				<swiper-item v-for="(page, pid) in emojiList" :key="pid">
					<view v-for="(em, eid) in page" :key="eid" @tap="addEmoji(em)"><image mode="widthFix" :src="'/static/img/emoji/' + em.url"></image></view>
				</swiper-item>
			</swiper> -->
				<!-- 更多功能 相册-拍照-红包 -->
				<view class="more-layer" :class="{ hidden: hideMore }">
					<view class="list">
						<view class="clearfix">
							<view class="box" @tap="chooseImage">
								<view class="icon tupian2"></view>
							</view>
							<view class="text" style="text-align: center;">相册</view>
						</view>
						<view class="clearfix">
							<view class="box" @tap="camera">
								<view class="icon paizhao"></view>
							</view>

							<view class="text" style="text-align: center;">拍照</view>
						</view>
						<view class="clearfix">
							<view class="box" @tap="video">
								<view class="icon">
									<image style="width:28px;height: 28px;padding-top: 7px; "
										src="../../static/pages/video.png"></image>
								</view>
							</view>

							<view class="text" style="text-align: center;">视频</view>
						</view>
						<view class="clearfix">
							<view class="box" @tap="getLocation">
								<view class="icon">
									<image style="width:28px;height: 28px;padding-top: 7px; "
										src="../../static/img/address.png"></image>
								</view>
							</view>
							<view class="text" style="text-align: center;">定位</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 底部输入栏 -->
			<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
				<!-- H5下不能录音，输入栏布局改动一下 -->
				<!-- #ifndef H5 -->
				<view class="voice">
					<view class="icon" :class="isVoice ? 'jianpan' : 'yuyin'" @tap="switchVoice"></view>
				</view>
				<!-- #endif -->
				<!-- #ifdef H5 -->
				<view class="more" @tap="showMore">
					<view class="icon add"></view>
				</view>
				<!-- #endif -->
				<view class="textbox">
					<view class="voice-mode" :class="[isVoice ? '' : 'hidden', recording ? 'recording' : '']"
						@touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd"
						@touchcancel="voiceCancel">
						{{ voiceTis }}
					</view>
					<view class="text-mode" :class="isVoice ? 'hidden' : ''">
						<view class="box"><textarea auto-height="true" v-model="textMsg" @focus="textareaFocus" />
						</view>
						<!-- 		<view class="em" @tap="chooseEmoji">
						<view class="icon biaoqing"></view>
					</view> -->
					</view>
				</view>
				<!-- #ifndef H5 -->
				<view class="more" @tap="showMore">
					<view class="icon add"></view>
				</view>
				<!-- #endif -->
				<view class="send" :class="isVoice ? 'hidden' : ''" @tap="sendText">
					<view class="btn">发送</view>
				</view>
			</view>

			<!-- 录音UI效果 -->
			<view class="record" :class="recording ? '' : 'hidden'">
				<view class="ing" :class="willStop ? 'hidden' : ''">
					<view class="icon luyin2"></view>
				</view>
				<view class="cancel" :class="willStop ? '' : 'hidden'">
					<view class="icon chehui"></view>
				</view>
				<view class="tis" :class="willStop ? 'change' : ''">{{ recordTis }}</view>
			</view>
		</view>
		<voiceChatModal></voiceChatModal>
		<video-chat></video-chat>
	</view>
</template>
<script>
	import userList from '../../commen/tim/user.js';
	import {
		mapState
	} from 'vuex';
	import chooseFile from '@/js_sdk/tencentcloud-plugin-cos/choose-file.js';
	import uploadFile from '@/js_sdk/tencentcloud-plugin-cos/upload-file.js';
	import getFileAccessUrl from '@/js_sdk/tencentcloud-plugin-cos/get-file-access-url.js';
	import voiceChatModal from '../../components/voice-chat-modal.vue'
	export default {
		data() {
			return {
				markers: [{}, {}, {}],
				mapState: false,
				addressList: [],
				poisdatas: [{}, {}, {}],
				title: 'map',
				latitude: 39.9,
				longitude: 116.4,
				SRC: '111111111111',
				//TIM变量
				conversationActive: null,
				toUserId: '',
				titleText: '',
				toUserInfo: null,
				userInfo: null,
				nextReqMessageID: '',
				count: 15,
				isCompleted: '',
				msgList: [],
				TIM: null,

				//文字消息
				textMsg: '',
				//消息列表
				isHistoryLoading: false,
				scrollAnimation: false,
				scrollTop: 0,
				scrollToView: '',

				msgImgList: [],
				myuid: 0,

				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: '手指上滑 取消发送',
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				recordLength: 0,

				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				// 抽屉参数
				popupLayerClass: '',
				// more参数
				hideMore: true,
				//表情定义
				hideEmoji: true,
				groupId: '',
				emojiList: this.$commen.emojiList,
				//表情图片图床名称 ，由于我上传的第三方图床名称会有改变，所以有此数据来做对应，您实际应用中应该不需要
				onlineEmoji: {
					'100.gif': 'AbNQgA.gif'
				},
				functionBox: '',
				funcBox_position: 0,
				h_groupInfo: null,
				peopleData: []
			};
		},
		components: {
			voiceChatModal
		},
		computed: {
			...mapState({
				currentMessageList: state => state.currentMessageList
			}),
		},
		watch: {
			currentMessageList(newVal, oldVal) {
				if (newVal){
					console.log(newVal)
					let that = this;
				}
					
				let data = newVal;
				for (let i = 0; i < newVal.length; i++) {
					if (newVal[i].avatar.indexOf('[') > -1) {
						data[i].avatar = JSON.parse(newVal[i].avatar)[0];
					} else if (newVal[i].avatar == "") {
						that.$utils.postrequest("/api/getuser", {
							user_id: newVal[i].from
						}, function(res) {
							if (res.code == 200) {
								data[i].avatar = res.data.avatar
							}
						})
					}
					if (newVal[i].payload.data == "mapFile" && newVal[i].payload.description != '') {
						if (typeof(newVal[i].payload.description) != "object") {
							newVal[i].payload.description = JSON.parse(newVal[i].payload.description)
						}
					}
					if (newVal[i].from == '@TIM#SYSTEM') {
						data.splice(i, 1);
					}
				}
				this.msgList = data;
				this.screenMsg(newVal, oldVal);
			},
			msgList(newVal, oldVal) {
				// console.log(newVal)
				this.$nextTick(() => {
					this.scrollTop = 9999999;
				})
			}
		},
		onLoad(option) {
			this.screenHeight = 'height:' + this.$systemInfo.screenHeight * 0.87 + 'px'
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
			let avatar_arr = JSON.parse(this.userInfo.avatar)
			this.userInfo.avatar = avatar_arr.shift();
			this.toUserInfo = uni.getStorageSync('chooseUser');
			let chooseAddress = uni.getStorageSync('chooseAddress');

			// this.toUserInfo.avatar = this.toUserInfo.avatar.substr(2,this.toUserInfo.avatar.length-4)
			this.toUserId = this.$store.state.toUserId;
			this.groupId = uni.getStorageSync('chooseGroup');
			this.titleText = uni.getStorageSync('titleText');
			this.conversationActive = this.$store.state.conversationActive;
			this.TIM = this.$TIM;
			//获取聊天对象的用户信息
			// userList.forEach(item=>{
			// 	if(this.toUserId == item.userId){
			// 		this.toUserInfo = item
			// 	}
			// })
			this.getMsgList();

			if (!!chooseAddress) {
				let msg = {
					text: chooseAddress
				};
				this.sendMsg(msg, 'text');
			}

			//语音自然播放结束
			this.AUDIO.onEnded(res => {
				this.playMsgid = null;
			});
			// #ifndef H5
			//录音开始事件
			this.RECORDER.onStart(e => {
				this.recordBegin(e);
			});
			//录音结束事件
			this.RECORDER.onStop(e => {
				this.recordEnd(e);
			});
			// #endif
			setTimeout(() => {
				if (!!option.message) {
					this.latitude = option.latitude
					this.longitude = option.longitude
					// console.log(option);
					let msg = {
						text: JSON.stringify(option)
					};
					this.sendMsg(msg, 'mapFile');
				}
			}, 300);
			this.getGroupInfo();
			this.getGroupPeople();
		},
		// onBackPress(events) {
		// 	if(events.from == "backbutton"){
		// 		uni.navigateBack({
		// 			delta:1
		// 		})
		// 	}
		// },
		onShow() {
			// debugger
			this.$nextTick(() => {
				this.scrollTop = 9999999;
			})

			// this.scrollToView = this.nextReqMessageID;
			// 通过 id 获取 nvue 子窗体  
			// const subNVue = uni.getSubNVueById('map_widget')  
			// 打开 nvue 子窗体  
			// subNVue.show('slide-in-left', 300, function(){  
			//     // 打开后进行一些操作...  
			// subNVue.setStyle({
			// 		top: '100px',  
			// 		left: '20px',  
			// 		width: '100px',  
			// 		height: '50px'
			// 	})
			// 	uni.$emit('page-popup', {  
			// 	    title: '我是一个title',  
			// 	    content: '我是data content'  
			// 	});
			//     //   
			// });  

			// 关闭 nvue 子窗体  
			// subNVue.hide('fade-out', 300)
		},
		onUnload() {
			//退出页面 将所有的会话内的消息设置为已读
			let promise = this.tim.setMessageRead({
				conversationID: this.conversationActive.conversationID
			});
			promise
				.then(function(imResponse) {
					// console.log('全部已读');
					// 已读上报成功
				})
				.catch(function(imError) {
					// 已读上报失败
					console.warn('setMessageRead error:', imError);
				});
		},
		methods: {
			// 获取用户头像
			toUserName(avtar) {
				let ids = this.peopleData.filter(item => {
					return item.avatar == avtar
				})
				let nick = '';
				if (Array.isArray(ids) && ids[0] && ids[0]["nick"]) nick = ids[0]["nick"]
				return nick
			},
			toAnnouncement() {
				uni.navigateTo({
					url: "/pages/announcement/index?groupId=" + this.groupId
				})
			},
			closeGroupInfoFun() {
				this.h_groupInfo = null;
			},
			getGroupInfo() {
				const that = this;
				this.$utils.postrequest("/api/tim/get_group_info", {
					GroupId: that.groupId
				}, res => {
					// console.log("群公告：" + res)
					// console.log(res)
					if (res.code == 200) {
						that.h_groupInfo = res.data.Notification;
					}
				})
			},
			toUserHome(id, avtar) {
				if (id) {
					uni.navigateTo({
						url: '/pages/my/mydongtai?id=' + id
					})
				} else {
					let ids = this.peopleData.filter(item => {
						return item.avatar == avtar
					})
					uni.navigateTo({
						url: '/pages/my/mydongtai?id=' + ids[0]["userID"]
					})
				}
			},
			hideMask() {
				this.functionBox = false
			},
			// 获取成员列表
			getGroupPeople() {
				let that = this;
				let promise = this.tim.getGroupMemberList({
					groupID: this.groupId,
					count: 999,
					offset: 0
				}); // 从0开始拉取30个群成员
				promise.then(function(imResponse) {
					// console.log(imResponse)
					for (let i = 0; i < imResponse.data.memberList.length; i++) {
						if (imResponse.data.memberList[i].avatar.indexOf("[") > -1) {
							imResponse.data.memberList[i].avatar = JSON.parse(imResponse.data.memberList[i]
								.avatar)[0]
						} else if (imResponse.data.memberList[i].avatar.indexOf(",") > -1) {
							imResponse.data.memberList[i].avatar = JSON.parse(imResponse.data.memberList[i]
								.avatar)[0]
						} else if (imResponse.data.memberList[i].avatar == "") {
							// imResponse.data.memberList.splice(i,1);
							that.$utils.postrequest("/api/getuser", {
								user_id: imResponse.data.memberList[i].userID
							}, function(res) {
								if (res.code == 200) {
									imResponse.data.memberList[i].avatar = res.data.avatar
									imResponse.data.memberList[i].nick = res.data.nickname
								}
							})
						}
					}
					imResponse.data.memberList.forEach((e, i) => {
						e.isLeader = 0
						if (e.userID == that.groupLeaderId) {
							e.isLeader = 1
						}
					})
					that.peopleData = imResponse.data.memberList;
				}).catch(function(imError) {
					console.warn('getGroupMemberList error:', imError);
				});
			},
			showFunctionBox(item) {
				this.copyData = item
				this.functionBox = item.ID
				let id = '.' + item.ID
				const query = uni.createSelectorQuery().in(this);
				query.select(id).boundingClientRect(data => {
					// console.log(data)
					let left = data.left + (data.width / 2) - 55
					let bottom = data.bottom
					this.funcBox_position = "left:" + left + 'px;'
				}).exec();
			},
			copyText() {
				let that = this
				uni.setClipboardData({
					data: that.copyData.payload.text,
					success: res => {
						that.functionBox = false
					}
				})
			},
			revokeMessage(message) {
				let that = this
				let promise = this.tim.revokeMessage(message);
				promise.then(function(imResponse) {
					that.functionBox = false
				}).catch(function(imError) {
					that.functionBox = false
					uni.showToast({
						title: '消息撤回超过了两分钟',
						icon: "none",
						success: res => {}
					})
				});
			},
			checkMyLocation(description) {
				uni.navigateTo({
					url: 'roomDetails/checkLocation/checkLocation?description=' + JSON.stringify(description)
				});
			},
			playVideo(data) {
				uni.navigateTo({
					url: "roomDetails/playVideo/playVideo?url=" + data
				})
			},
			collect() {
				// #ifdef APP-PLUS
				//触发监听  并传值
				uni.$emit('goods_bottom_setval', {
					isCollected: this.isCollected
				})
				// #endif
			},
			videoErrorCallback: function(e) {
				// console.log('视频错误信息:')
				// console.log(e.target.errMsg)
			},
			video() {
				let that = this;
				uni.chooseVideo({
					count: 1,
					sourceType: ['camera', 'album'],
					success: function(res) {
						let imgHref = res.tempFilePath;
						uni.uploadFile({
							url: 'http://c.voofan.com/api/upload',
							filePath: imgHref,
							name: 'file',
							success: datas => {
								that.sendMsg(JSON.parse(datas.data).data, 'video');
								that.hideDrawer()
							}
						});
					}
				});
			},
			sendAddres(data) {
				// "city": "重庆市",
				let msg = {
					text: data.callout.content
				};
				this.sendMsg(msg, 'text');
				this.mapState = false;
				this.markers = [];
			},
			groupInfo() {
				// pages/tim/roomDetails/roomDetails
				uni.setStorageSync('chooseGroup', this.conversationActive.conversationID);
				uni.navigateTo({
					url: '/pages/tim/roomDetails/roomDetails'
				});
			},
			//聊天的节点加上外层的div
			nodesFliter(str) {
				let nodeStr = '<div style="align-items: center;word-wrap:break-word;">' + str + '</div>';
				return nodeStr;
			},
			back() {
				uni.navigateBack()
				// uni.switchTab({
				// 	url:"../message/index"
				// })
			},
			//时间过滤
			timeFliter(timer) {
				let timeData = new Date(timer * 1000);
				let str = this.$commen.dateTimeFliter(timeData);
				return str;
			},
			// 接受消息(定位消息)
			screenMsg(newVal, oldVal) {
				if (newVal[0].ID && oldVal.length > 0 && oldVal[0].ID) {
					if (newVal[0].ID != oldVal[0].ID && newVal.length >= this.count) {
						this.$nextTick(() => {
							this.scrollToView = oldVal[0].ID;
						});
					} else {
						this.$nextTick(() => {
							this.scrollToView = newVal[newVal.length - 1].ID;
						});
					}
				} else {
					// this.$nextTick(() => {
					// 	this.scrollToView = newVal[newVal.length - 1].ID;
					// });
				}
			},
			//触发滑动到顶部(加载历史信息记录)
			loadHistory(e) {
				// 更多消息列表
				let conversationID = this.conversationActive.conversationID;
				let promise = this.tim.getMessageList({
					conversationID: conversationID,
					nextReqMessageID: this.nextReqMessageID,
					count: this.count
				});
				promise.then(res => {
					this.$store.commit('unshiftCurrentMessageList', res.data.messageList);
					this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
					this.isCompleted = res.data.isCompleted;
				});
				//这段代码很重要，不然每次加载历史数据都会跳到顶部
				this.$nextTick(function() {
					this.scrollToView = this.nextReqMessageID; //跳转上次的第一行信息位置
					this.$nextTick(function() {
						this.scrollAnimation = true; //恢复滚动动画
					});
				});
				this.isHistoryLoading = false;
			},
			// 加载初始页面消息
			getMsgList() {
				// 历史消息列表
				let conversationID = this.conversationActive.conversationID;
				if (conversationID) {
					let promise = this.tim.getMessageList({
						conversationID: conversationID,
						count: this.count
					});
					promise.then(res => {
						let messageList = res.data.messageList
						messageList.forEach((e, i) => {
							if (e.isRevoked == true) {
								messageList.splice(i, 1)
							}
						})
						this.$store.commit('pushCurrentMessageList', messageList);
						this.nextReqMessageID = res.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
						this.isCompleted = res.data.isCompleted;
						// this.scrollToView = res.data.messageList[res.data.messageList.length - 1].ID;
						if (messageList.length < 15) {
							this.loadHistory()
						}
					});
				} else {}

				// 滚动到底部
				setTimeout(() => {
					//进入页面滚动到底部
					this.$nextTick(function() {
						this.scrollTop = 9999;
						this.scrollAnimation = true;
					});
				}, 1000);
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(content) {
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
				let maxH = uni.upx2px(350); //350是定义消息图片最大高度
				if (content.w > maxW || content.h > maxH) {
					let scale = content.w / content.h;
					content.w = scale > 1 ? maxW : maxH * scale;
					content.h = scale > 1 ? maxW / scale : maxH;
				}
				return content;
			},
			//更多功能(点击+弹出)
			showMore() {
				this.isVoice = false;
				this.hideEmoji = true;
				if (this.hideMore) {
					this.hideMore = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			// 打开抽屉
			openDrawer() {
				this.popupLayerClass = 'showLayer';
			},
			// 隐藏抽屉
			hideDrawer() {
				this.popupLayerClass = '';
				setTimeout(() => {
					this.hideMore = true;
					this.hideEmoji = true;
				}, 150);
			},
			// 选择图片发送
			chooseImage() {
				this.getImage('album');
			},
			//拍照发送
			camera() {
				this.getImage('camera');
			},
			//选照片 or 拍照
			getImage(type) {
				let that = this;
				this.hideDrawer();
				uni.chooseImage({
					sourceType: [type],
					count: 1,
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: res => {
						let imgHref = res.tempFilePaths[0];
						uni.uploadFile({
							url: 'http://c.voofan.com/api/upload',
							filePath: imgHref,
							name: 'file',
							success: datas => {
								that.sendMsg(JSON.parse(datas.data).data, 'img');
							}
						});
						// that.$utils.postrequest("/api/upload", formdata, function (resData) {
						//    if(resData.code==200){
						// 		that.sendMsg(resData.data, 'img');
						// 	}
						// })
					}
				});
			},
			// 选择表情
			chooseEmoji() {
				this.hideMore = true;
				if (this.hideEmoji) {
					this.hideEmoji = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			//添加表情
			addEmoji(em) {
				this.textMsg += em.alt;
			},
			// 获取定位
			getLocation() {
				let that = this;
				uni.navigateTo({
					url: '/pages/tim/map?type=1'
				});
			},
			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus() {
				if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
					this.hideDrawer();
				}
			},
			// 发送文字消息
			sendText() {
				this.hideDrawer(); //隐藏抽屉
				if (!this.textMsg) {
					return;
				}
				let content = this.replaceEmoji(this.textMsg);
				let msg = {
					text: content
				};
				this.sendMsg(msg, 'text');
				this.textMsg = ''; //清空输入框
			},
			//替换表情符号为图片
			replaceEmoji(str) {
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
					// console.log('item: ' + item);
					for (let i = 0; i < this.emojiList.length; i++) {
						let row = this.emojiList[i];
						for (let j = 0; j < row.length; j++) {
							let EM = row[j];
							if (EM.alt == item) {
								//在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径
								//比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
								let onlinePath = 'https://s2.ax1x.com/2019/04/12/';
								let imgstr = '<img src="' + onlinePath + this.onlineEmoji[EM.url] + '">';
								// console.log('imgstr: ' + imgstr);
								return imgstr;
							}
						}
					}
				});
				return replacedStr;
			},

			// 发送消息
			sendMsg(content, type) {
				let that = this;
				let message;
				// console.log(content,type);
				if (type == 'text') {
					message = this.tim.createTextMessage({
						// to: that.toUserId.toString(),
						to: that.groupId,
						userId: that.userInfo.id,
						conversationType: that.$TIM.TYPES.CONV_GROUP,
						payload: {
							text: content.text
						}
					});
				} else if (type == 'img') {
					message = this.tim.createCustomMessage({
						// to: that.toUserId.toString(),
						to: that.groupId,
						userId: that.userInfo.id,
						conversationType: that.$TIM.TYPES.CONV_GROUP,
						payload: {
							data: 'chatFile', // 用于标识该消息类型
							description: content, // 用于装载url
							extension: ''
						}
					});
				} else if (type == 'voice') {
					let href = content.url.substr(0, content.url.indexOf('mp3') + 3);
					message = that.tim.createCustomMessage({
						// to: this.toUserInfo.id,
						to: that.groupId,
						userId: that.userInfo.id,
						conversationType: that.$TIM.TYPES.CONV_GROUP,
						// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
						// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
						// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
						payload: {
							data: 'voiceFile', // 用于标识该消息类型
							description: href, // 用于装载url
							extension: content.length
						}
					});
				} else if (type == 'video') {
					message = that.tim.createCustomMessage({
						// to: this.toUserInfo.id,
						to: that.groupId,
						userId: that.userInfo.id,
						conversationType: that.$TIM.TYPES.CONV_GROUP,
						// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
						// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
						// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
						payload: {
							data: 'videoFile', // 用于标识该消息类型
							description: content, // 用于装载url
							extension: ''
						}
					});
				} else if (type == 'mapFile') {
					message = that.tim.createCustomMessage({
						// to: this.toUserInfo.id,
						to: that.groupId,
						userId: that.userInfo.id,
						conversationType: that.$TIM.TYPES.CONV_GROUP,
						// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
						// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
						// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
						payload: {
							data: 'mapFile', // 用于标识该消息类型
							description: content.text, // 用于装载url
							extension: ''
						}
					});
				}
				// console.log(message);
				this.$store.commit('pushCurrentMessageList', message);
				let pomise = this.tim.sendMessage(message);
				pomise.then(res => {
					this.$nextTick(() => {
						// 滚动到底
						this.scrollToView = res.data.message.ID;
					});
				});
			},

			// 添加文字消息到列表
			addTextMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加语音消息到列表
			addVoiceMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg) {
				msg.content = this.setPicSize(msg.payload.description);
				this.msgImgList.push(msg.payload.description);
				this.msgList.push(msg);
			},
			addRedEnvelopeMsg(msg) {
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg) {
				this.msgList.push(msg);
			},

			sendSystemMsg(content, type) {
				let lastid = this.msgList[this.msgList.length - 1].msg.id;
				lastid++;
				let row = {
					type: 'system',
					msg: {
						id: lastid,
						type: type,
						content: content
					}
				};
				this.screenMsg(row);
			},
			//领取详情
			toDetails(rid) {
				uni.navigateTo({
					url: 'HM-details/HM-details?rid=' + rid
				});
			},
			// 预览图片
			showPic(msg) {
				uni.previewImage({
					indicator: 'none',
					current: msg.payload.description,
					urls: [msg.payload.description]
				});
			},
			// 播放语音
			playVoice(msg) {
				this.playMsgid = msg.ID;
				this.AUDIO.src = msg.payload.description;
				this.$nextTick(function() {
					this.AUDIO.play();
				});
			},
			// 录音开始
			voiceBegin(e) {
				if (e.touches.length > 1) {
					return;
				}
				this.initPoint.Y = e.touches[0].clientY;
				this.initPoint.identifier = e.touches[0].identifier;
				this.RECORDER.start({
					format: 'mp3'
				}); //录音开始,
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				this.recordTimer = setInterval(() => {
					this.recordLength++;
				}, 1000);
			},
			// 录音被打断
			voiceCancel() {
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送';
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				if (!this.recording) {
					return;
				}
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送';
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送';
				}
			},
			// 结束录音
			voiceEnd(e) {
				if (!this.recording) {
					return;
				}
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送';
				this.RECORDER.stop(); //录音结束
			},
			//录音结束(回调文件)
			async recordEnd(e) {
				let progress1 = 0;
				let interval;
				let that = this;
				clearInterval(this.recordTimer);
				uni.uploadFile({
					url: 'http://c.voofan.com/api/upload',
					filePath: e.tempFilePath,
					name: 'file',
					success: datas => {
						let msg = {
							href: '',
							length: ''
						};
						msg.url = JSON.parse(datas.data).data;
						let min = parseInt(that.recordLength / 60);
						let sec = that.recordLength % 60;
						min = min < 10 ? '0' + min : min;
						sec = sec < 10 ? '0' + sec : sec;
						msg.length = min + ':' + sec;
						this.sendMsg(msg, 'voice');
					}
				});
				// const key = await uploadFile(e.tempFilePath, null, ({ progress }) => {
				// 	progress1 = progress;
				// 	// console.log(`文件上传中(${progress}%)`);
				// });
				// let msg = {
				// 	href: '',
				// 	length: ''
				// };
				// const url = await getFileAccessUrl(key);
				// msg.url = url;
				// let min = parseInt(that.recordLength / 60);
				// let sec = that.recordLength % 60;
				// min = min < 10 ? '0' + min : min;
				// sec = sec < 10 ? '0' + sec : sec;
				// msg.length = min + ':' + sec;
				// this.sendMsg(msg, 'voice');
			},
			// 切换语音/文字输入
			switchVoice() {
				this.hideDrawer();
				this.isVoice = this.isVoice ? false : true;
			},
			discard() {
				return;
			}
		}
	};
</script>
<style lang="scss">
	@import '@/static/HM-chat/css/style.scss';
</style>
<style lang="scss">
	.box-pandding {
		padding: 15upx 20upx;
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;
		width: 100%;
		height: 100vh;
		/* background-color:rgba(0,0,0,0.2); */
	}

	.funcBtn {
		width: 200rpx;
		height: 50rpx;
		background-color: rgba(0, 0, 0, 0.8);
		border-radius: 15rpx;
		color: #FFFFFF;
		float: right;
		margin-top: -50rpx;
		display: flex;
		align-items: center;
		position: absolute;
		justify-content: center;
		z-index: 9999;
	}

	.func {
		width: 100rpx;
		text-align: center;
	}

	.map {
		position: relative;
		overflow: hidden;
	}

	.map-text {
		position: absolute;
		top: 0px;
		padding: 3px;
	}

	.map-content1 {
		font-size: 24rpx;
		height: 50rpx;
		width: 200rpx;
		background-color: rgb(46, 197, 244);
		color: #F1F1F1;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		border-radius: 16rpx;
	}

	.nav {
		display: flex;
		flex-wrap: wrap;
		margin: 109rpx 31rpx 20rpx 31rpx;
	}

	.back {
		margin-top: 12rpx;
		width: 40rpx;
		height: 40rpx;
	}

	.nav-text {
		width: 300rpx;
		font-size: 32rpx;
		margin: 0 auto;
		text-align: center;
		line-height: 62rpx;
	}

	.issue {
		// margin-left: 290rpx;
		width: 64rpx;
		height: 62rpx;
	}

	.status_bar {
		/*自定义标题*/
		height: var(--status-bar-height);
	}

	.status_bar {
		position: fixed;
		width: 100%;
		top: 0;
		left: 0;
		height: 44px;
		line-height: 44px;
		/* background: #c00; */
		z-index: 999;
		background-color: rgb(248, 248, 248);
		color: rgb(0, 0, 0);
		text-align: center;
	}

	.nav_logo {
		float: left;
		margin-left: 22rpx;
		margin-top: 22rpx;
		margin-right: 15rpx;
		display: block;
		width: 61rpx;
		height: 47rpx;
	}

	.uni-btn-icon {
		vertical-align: middle;
	}

	.uni-page-head .uni-page-head-hd {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		font-size: 16px;
	}

	.uni-page-head .uni-page-head * {
		box-sizing: border-box;
	}

	.uni-page-head-btn {
		position: relative;
		width: auto;
		margin: 0 2px;
		word-break: keep-all;
		white-space: pre;
		cursor: pointer;
	}

	.msg-list {
		top: 180rpx !important;
	}

	.uni-page-head .uni-page-head-bd {
		position: absolute;
		left: 70px;
		right: 70px;
		min-width: 0;
		-webkit-user-select: auto;
		user-select: auto;
	}

	.uni-page-head .uni-page-head__title {
		font-weight: 700;
		font-size: 16px;
		line-height: 30px;
		text-align: center;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}

	.uni-page-head {
		position: fixed;
		left: var(--window-left);
		right: var(--window-right);
		top: 0;
		height: 44px;
		height: calc(44px + constant(safe-area-inset-top));
		height: calc(44px + env(safe-area-inset-top));
		padding: 7px 3px;
		padding-top: calc(7px + constant(safe-area-inset-top));
		padding-top: calc(7px + env(safe-area-inset-top));
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		overflow: hidden;
		-webkit-box-pack: justify;
		-webkit-justify-content: space-between;
		justify-content: space-between;
		box-sizing: border-box;
		z-index: 998;
		-webkit-transition-property: all;
		transition-property: all;
	}
</style>
<style>
	.page-body {
		z-index: 99999999;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}

	.address-list-box {
		height: 30px;
		line-height: 30px;
		height: 30px;
		line-height: 30px;
		border-bottom: 1px #ddd solid;
		padding-left: 10px;
	}

	.left-img {
		width: 5px;
		height: 12px;
		margin-top: 12px;

		background: url(../../static/pages/message_right.png) no-repeat;
		background-size: cover;
	}

	.right-img {
		width: 5px;
		height: 12px;
		margin-top: 6px;
		background: url(../../static/pages/message_left.png) no-repeat;
		background-size: cover;
	}

	.chatImg {
		width: 160rpx;
		/* height: 240rpx; */
		display: flex;
		align-items: center;
	}

	.chatImg image {
		max-width: 160rpx;
		border-radius: 15rpx;
	}

	.announcement {
		width: 654rpx;
		background: #FFFFFF;
		border-radius: 10rpx;
		margin: auto;
		position: relative;
		display: flex;
		justify-content: center;
		position: fixed;
		top: 180rpx;
		left: 48rpx;
		z-index: 9999;
	}

	.a_close {
		width: 19rpx;
		padding: 10rpx;
		height: 19rpx;
		position: absolute;
		right: 8rpx;
		top: 0rpx;
		z-index: 999;
	}

	.a_close image {
		width: 100%;
		height: 100%;
	}

	.a_content {
		width: 654rpx;
		height: 148rpx;
		background-image: url(../../static/img/a_content_bg.png);
		background-repeat: no-repeat;
		background-size: 100% 100%;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.a_c_head {
		width: 360rpx;
		height: 38rpx;
		position: absolute;
		top: -17rpx;
	}

	.a_c_head image {
		width: 100%;
		height: 100%;
	}

	.a_c_text {
		margin-top: 47rpx;
		width: 624rpx;
		font-size: 26rpx;
		font-weight: 500;
		color: #333333;
		line-height: 36rpx;
		position: relative;
	}

	.a_c_text_particulars {
		position: absolute;
		right: 0;
		color: #FB6A32;
	}
</style>
<style lang="scss">
	@import '@/graceUI/graceUI.css';
</style>
